package theOrbalEra.common.network;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.IOException;

import theOrbalEra.common.player.PlayerHandler;
import theOrbalEra.common.util.DefultValue;
import theOrbalEra.common.util.idList.PacketId;
import theOrbalEra.common.util.idList.PlayerActionList;

import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.packet.Packet250CustomPayload;

import com.google.common.io.ByteArrayDataInput;

import cpw.mods.fml.common.FMLCommonHandler;
import cpw.mods.fml.common.network.PacketDispatcher;
import cpw.mods.fml.common.network.Player;

public class PacketPlayerHandler extends PacketBase {
	public static PacketPlayerHandler instance =new PacketPlayerHandler();

	@Override
	void readClient(int id, ByteArrayDataInput data, Object[] extradata) {


	}

	

	@Override
	void readServer(int id, ByteArrayDataInput data, Object[] extradata) {
		int action=data.readInt();
		int dat=data.readInt();
		EntityPlayer player=(EntityPlayer) extradata[0];
		switch(action){
		case PlayerActionList.REBORN:
			reborn(player);
			break;
		case PlayerActionList.HURT:
			hurt(player,dat);
			break;
		case PlayerActionList.EXPERIENCE_UP:
			experienceUP(player,dat);
			break;
		case PlayerActionList.DEAD:
			dead(player);
			break;
		}
	
	

	}
	
	public static void playerAction(int ActionId,int data,String name){
		
		ByteArrayOutputStream bos = new ByteArrayOutputStream(140);
        DataOutputStream dos = new DataOutputStream(bos);

        try
        {
		dos.writeInt(PacketId.PLAYER_ACTION);
		dos.writeInt(ActionId);
		dos.writeInt(data);
		dos.writeUTF(name);
		
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }

        Packet250CustomPayload pkt = new Packet250CustomPayload();
        pkt.channel = DefultValue.channel;
        pkt.data = bos.toByteArray();
        pkt.length = bos.size();
        pkt.isChunkDataPacket = false;
        EntityPlayerMP player = FMLCommonHandler.instance().getMinecraftServerInstance().getConfigurationManager().getPlayerForUsername(name);
        PacketDispatcher.sendPacketToPlayer(pkt, (Player) player);
        
	}
	
	
	private void dead(EntityPlayer player) {
		PlayerHandler.getPlayer(player.username).dead();
		
	}
	private void experienceUP(EntityPlayer player, int dat) {
		PlayerHandler.getPlayer(player.username).experienceUP(dat);
		
	}

	private void hurt(EntityPlayer player, int dat) {
		PlayerHandler.getPlayer(player.username).playerHurt(dat);
		
	}

	private void reborn(EntityPlayer player) {
		PlayerHandler.getPlayer(player.username).respawn();
		
	}


}
